package com.zoe.onelink.logging.biz.context;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Stack;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-10-12
 */
public class BizLogContext {

    private static final InheritableThreadLocal<Stack<Map<String, Object>>> INNER = new InheritableThreadLocal<>();

    private static Stack<Map<String, Object>> pushEmptyStack() {
        Stack<Map<String, Object>> stack = Optional.ofNullable(INNER.get()).orElseGet(() -> {
            Stack<Map<String, Object>> innerStack = new Stack<>();
            INNER.set(innerStack);
            return innerStack;
        });
        stack.push(new HashMap<>(4));
        return stack;
    }

    public static void putVal(String key, Object value) {
        Stack<Map<String, Object>> stack = Optional.ofNullable(INNER.get()).orElseGet(BizLogContext::pushEmptyStack);
        stack.peek().put(key, value);
    }

    public static void putValMap(Map<String, Object> map) {
        if (map == null || map.size() == 0) {
            return;
        }
        map.forEach(BizLogContext::putVal);
    }

    public static Map<String, Object> getValMap() {
        Stack<Map<String, Object>> stack = INNER.get();
        if (stack == null) {
            return null;
        }
        if (stack.empty()) {
            return null;
        }
        return stack.peek();
    }

    public static Object getVal(String key) {
        Map<String, Object> map = getValMap();
        if (map == null || map.size() == 0) {
            return null;
        }
        return map.get(key);
    }

    public static void clear() {
        Stack<Map<String, Object>> stack = INNER.get();
        if (stack == null || stack.empty()) {
            return;
        }
        stack.pop();
    }

}
